package com.bwie.task;

import cn.hutool.core.bean.BeanUtil;
import com.bwie.domain.TbLog;
import com.bwie.es.EsLog;
import com.bwie.mapper.TbLogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SyncLogTask {

    @Autowired
    TbLogMapper tbLogMapper;

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 每1分钟同步一次日志
     */
    @Scheduled(cron = "0 0/1 * * * ? ")
    public void syncLog(){
        System.out.println("开始同步日志...");
        // 手动创建索引
        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(EsLog.class);
        if(!indexOps.exists()) {
            // 索引不存在，创建索引
            indexOps.create();

            // 手动创建映射
            Document mapping = indexOps.createMapping();
            indexOps.putMapping(mapping);
        }

        //-- 读取日志列表
        List<TbLog> tbLogs = tbLogMapper.selectList(null);

        //-- 存储到ES中
        for (TbLog tbLog : tbLogs) {
            EsLog esLog = BeanUtil.toBean(tbLog, EsLog.class);
            elasticsearchRestTemplate.save(esLog);
        }

        System.out.println("同步日志结束...");
    }

}
